<template>
  <div class="student-management-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <div class="header-title">
            <el-icon color="#E6A23C"><School /></el-icon>
            <span>学生认证管理</span>
          </div>
          <div class="header-actions">
            <el-button type="primary" @click="refreshData">
              <el-icon><Refresh /></el-icon>
              刷新数据
            </el-button>
          </div>
        </div>
      </template>

      <!-- 学生筛选 -->
      <div class="filter-container">
        <el-form :inline="true" :model="filters" class="filter-form">
          <el-form-item label="学校">
            <el-select v-model="filters.schoolName" placeholder="全部学校" clearable>
              <el-option 
                v-for="school in schoolList" 
                :key="school" 
                :label="school" 
                :value="school" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="毕业年份">
            <el-select v-model="filters.graduationYear" placeholder="全部年份" clearable>
              <el-option 
                v-for="year in graduationYearList" 
                :key="year" 
                :label="year + '年'" 
                :value="year" 
              />
            </el-select>
          </el-form-item>
          <el-form-item label="搜索">
            <el-input v-model="filters.search" placeholder="姓名/学号/身份证号" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchStudents">搜索</el-button>
            <el-button @click="resetFilters">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 学生统计 -->
      <div class="statistics-container">
        <el-row :gutter="16">
          <el-col :span="6">
            <el-statistic title="认证学生总数" :value="total" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="学校数量" :value="schoolList.length" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="本年度毕业" :value="currentYearGraduates" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="今日新增" :value="todayNewStudents" />
          </el-col>
        </el-row>
      </div>

      <!-- 学生列表 -->
      <div class="students-list">
        <el-table
          :data="studentsList"
          border
          style="width: 100%"
          v-loading="loading"
        >
          <el-table-column prop="id" label="ID" width="80" />
          <el-table-column prop="realName" label="真实姓名" width="120" />
          <el-table-column prop="idCardNumber" label="身份证号" width="180">
            <template #default="scope">
              {{ maskIdCard(scope.row.idCardNumber) }}
            </template>
          </el-table-column>
          <el-table-column prop="schoolName" label="学校名称" width="150" />
          <el-table-column prop="schoolId" label="学号" width="120" />
          <el-table-column prop="graduationYear" label="毕业年份" width="100">
            <template #default="scope">
              {{ scope.row.graduationYear }}年
            </template>
          </el-table-column>
          <el-table-column label="学生证" width="100" align="center">
            <template #default="scope">
              <el-button 
                v-if="scope.row.studentCardUrl" 
                size="small" 
                type="primary" 
                @click="viewStudentCard(scope.row.studentCardUrl)"
              >
                查看
              </el-button>
              <span v-else class="no-data">未上传</span>
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="认证时间" width="180">
            <template #default="scope">
              {{ formatDate(scope.row.createTime) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="160">
            <template #default="scope">
              <el-button size="small" type="info" @click="viewDetails(scope.row)">详情</el-button>
              <el-button 
                size="small" 
                type="danger" 
                @click="cancelBinding(scope.row)"
              >
                取消认证
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 学生详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="学生认证详情"
      width="600px"
    >
      <div class="detail-content" v-if="currentStudent">
        <el-descriptions title="基本信息" :column="2" border>
          <el-descriptions-item label="学生ID">{{ currentStudent.id }}</el-descriptions-item>
          <el-descriptions-item label="用户ID">{{ currentStudent.userId }}</el-descriptions-item>
          <el-descriptions-item label="真实姓名">{{ currentStudent.realName }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ currentStudent.idCardNumber }}</el-descriptions-item>
          <el-descriptions-item label="学校名称">{{ currentStudent.schoolName }}</el-descriptions-item>
          <el-descriptions-item label="学号">{{ currentStudent.schoolId }}</el-descriptions-item>
          <el-descriptions-item label="毕业年份">{{ currentStudent.graduationYear }}年</el-descriptions-item>
          <el-descriptions-item label="认证时间">{{ formatDate(currentStudent.createTime) }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <div v-if="currentStudent.studentCardUrl">
          <h4>学生证照片</h4>
          <el-image
            :src="currentStudent.studentCardUrl"
            :preview-src-list="[currentStudent.studentCardUrl]"
            fit="contain"
            style="width: 100%; max-height: 300px;"
          />
        </div>
        <div v-else>
          <el-alert title="未上传学生证照片" type="warning" :closable="false" />
        </div>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          <el-button 
            type="danger" 
            @click="cancelBindingFromDetail"
            v-if="currentStudent"
          >
            取消认证
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 学生证查看对话框 -->
    <el-dialog
      v-model="imageDialogVisible"
      title="学生证照片"
      width="500px"
    >
      <el-image
        :src="currentImageUrl"
        :preview-src-list="[currentImageUrl]"
        fit="contain"
        style="width: 100%;"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { School, Refresh } from '@element-plus/icons-vue'
import { getAllStudents, cancelStudentBinding } from '@/api/user'

// 检查是否有adminRoot权限
const checkAdminRoot = () => {
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
  if (userInfo.phone !== 'adminRoot') {
    ElMessage.error('您没有权限访问此页面')
    window.location.href = '/'
    return false
  }
  return true
}

// 加载状态
const loading = ref(false)

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 筛选条件
const filters = reactive({
  schoolName: '',
  graduationYear: '',
  search: ''
})

// 学生列表数据
const studentsList = ref([])
const originalStudentsList = ref([])

// 学校列表和毕业年份列表
const schoolList = computed(() => {
  const schools = [...new Set(originalStudentsList.value.map(student => student.schoolName))]
  return schools.filter(school => school)
})

const graduationYearList = computed(() => {
  const years = [...new Set(originalStudentsList.value.map(student => student.graduationYear))]
  return years.filter(year => year).sort((a, b) => b - a)
})

// 统计数据
const currentYearGraduates = computed(() => {
  const currentYear = new Date().getFullYear()
  return studentsList.value.filter(student => student.graduationYear === currentYear).length
})

const todayNewStudents = computed(() => {
  const today = new Date().toDateString()
  return studentsList.value.filter(student => {
    const createDate = new Date(student.createTime).toDateString()
    return createDate === today
  }).length
})

// 对话框相关
const detailDialogVisible = ref(false)
const imageDialogVisible = ref(false)
const currentStudent = ref(null)
const currentImageUrl = ref('')

// 应用前端筛选
const applyFilters = () => {
  let filteredList = [...originalStudentsList.value]
  
  // 按学校筛选
  if (filters.schoolName) {
    filteredList = filteredList.filter(student => student.schoolName === filters.schoolName)
  }
  
  // 按毕业年份筛选
  if (filters.graduationYear) {
    filteredList = filteredList.filter(student => student.graduationYear === filters.graduationYear)
  }
  
  // 按搜索关键词筛选
  if (filters.search) {
    const search = filters.search.toLowerCase()
    filteredList = filteredList.filter(student => 
      (student.realName && student.realName.toLowerCase().includes(search)) ||
      (student.schoolId && student.schoolId.toString().includes(search)) ||
      (student.idCardNumber && student.idCardNumber.toLowerCase().includes(search))
    )
  }
  
  studentsList.value = filteredList
  total.value = filteredList.length
}

// 日期格式化函数
const formatDate = (dateTime) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

// 身份证号脱敏
const maskIdCard = (idCard) => {
  if (!idCard || idCard.length < 8) return idCard
  return idCard.substring(0, 4) + '****' + idCard.substring(idCard.length - 4)
}

// 获取学生列表
const fetchStudentsList = () => {
  loading.value = true
  
  getAllStudents()
    .then(response => {
      if (response.code === 1) {
        originalStudentsList.value = response.data || []
        applyFilters()
      } else {
        ElMessage.error(response.msg || '获取学生列表失败')
      }
    })
    .catch(error => {
      console.error('获取学生列表失败', error)
      ElMessage.error('获取学生列表失败')
    })
    .finally(() => {
      loading.value = false
    })
}

// 刷新数据
const refreshData = () => {
  fetchStudentsList()
}

// 重置筛选条件
const resetFilters = () => {
  filters.schoolName = ''
  filters.graduationYear = ''
  filters.search = ''
  applyFilters()
}

// 搜索学生
const searchStudents = () => {
  currentPage.value = 1
  applyFilters()
}

// 处理页面大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  applyFilters()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  applyFilters()
}

// 查看学生证
const viewStudentCard = (imageUrl) => {
  currentImageUrl.value = imageUrl
  imageDialogVisible.value = true
}

// 查看详情
const viewDetails = (student) => {
  currentStudent.value = student
  detailDialogVisible.value = true
}

// 取消认证绑定
const cancelBinding = (student) => {
  ElMessageBox.confirm(
    `确定要取消 ${student.realName} 的学生认证吗？此操作不可恢复！`,
    '取消学生认证',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  )
  .then(() => {
    cancelStudentBinding(student.userId)
      .then(response => {
        if (response.code === 1) {
          ElMessage.success('取消认证成功')
          // 从列表中移除
          originalStudentsList.value = originalStudentsList.value.filter(item => item.id !== student.id)
          applyFilters()
        } else {
          ElMessage.error(response.msg || '取消认证失败')
        }
      })
      .catch(error => {
        console.error('取消认证失败', error)
        ElMessage.error('取消认证失败')
      })
  })
  .catch(() => {})
}

// 从详情对话框取消认证
const cancelBindingFromDetail = () => {
  detailDialogVisible.value = false
  cancelBinding(currentStudent.value)
}

// 组件挂载后执行
onMounted(() => {
  if (checkAdminRoot()) {
    fetchStudentsList()
  }
})
</script>

<style scoped>
.student-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  display: flex;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
}

.header-title .el-icon {
  margin-right: 8px;
  font-size: 20px;
}

.filter-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.statistics-container {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.students-list {
  margin-top: 20px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.no-data {
  color: #909399;
  font-size: 12px;
}

.detail-content {
  max-height: 60vh;
  overflow-y: auto;
}
</style> 